package org.zju.demo.shoppingdemo.activity;

import android.annotation.TargetApi;
import android.app.ActionBar;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import org.zju.demo.shoppingdemo.R;
import org.zju.demo.shoppingdemo.UIUtils.ActionBarDrawerToggle;
import org.zju.demo.shoppingdemo.UIUtils.DrawerArrowDrawable;
import org.zju.demo.shoppingdemo.adapter.DrawerListAdapter;
import org.zju.demo.shoppingdemo.adapter.ProductListAdapter;
import org.zju.demo.shoppingdemo.controller.ShoppingController;
import org.zju.demo.shoppingdemo.model.ContentModel;
import org.zju.demo.shoppingdemo.model.Product;
import org.zju.demo.shoppingdemo.model.Request.BaseModel;
import org.zju.demo.shoppingdemo.model.StaggeredGridView;
import org.zju.demo.shoppingdemo.model.response.BaseResponse;
import org.zju.demo.shoppingdemo.model.response.ResponseHotJson;
import org.zju.demo.shoppingdemo.model.response.ResponseProduct;
import org.zju.demo.shoppingdemo.utils.Constant;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ZJDX on 2015/9/13.
 */
public class WelcomeActivity extends CommonActivity implements AbsListView.OnScrollListener, AbsListView.OnItemClickListener, AdapterView.OnItemLongClickListener {


    private Toolbar toolbar;

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */

    private CharSequence mTitle;


    private ListView productListView;
    private List<Product> productList;
    private ProductListAdapter pAdapter;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private DrawerArrowDrawable drawerArrow;
    private boolean drawerArrowColor;
    private List<ContentModel> list;
    private Button transBtn;
    private static final String TAG = "WelcomeActivity";
    public static final String SAVED_DATA_KEY = "SAVED_DATA";

    private StaggeredGridView mGridView;
    private boolean mHasRequestedMore;
    //private SampleAdapter mAdapter;
    private DrawerListAdapter adapter;
    private ArrayList<String> mData;
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.welcome);
        prepareData();
        pAdapter = new ProductListAdapter(this, productList);
        mGridView = (StaggeredGridView) findViewById(R.id.activity_sgv);
        LayoutInflater layoutInflater = getLayoutInflater();

        View header = layoutInflater.inflate(R.layout.list_item_header_footer, null);
        View footer = layoutInflater.inflate(R.layout.list_item_header_footer, null);
        TextView txtHeaderTitle = (TextView) header.findViewById(R.id.txt_title);
        TextView txtFooterTitle =  (TextView) footer.findViewById(R.id.txt_title);
        txtHeaderTitle.setText(" ");
        txtFooterTitle.setText(" ");

        mGridView.addHeaderView(header);
        mGridView.addFooterView(footer);

     /*  mAdapter = new SampleAdapter(this, R.id.txt_line1);
        // do we have saved data?
        if (savedInstanceState != null) {
            mData = savedInstanceState.getStringArrayList(SAVED_DATA_KEY);
        }

        if (mData == null) {
            mData = SampleData.generateSampleData();
        }

        for (String data : mData) {
            mAdapter.add(data);
        }
*/
        mGridView.setAdapter(pAdapter);
        Log.d(TAG,"  mGridView.setAdapter(pAdapter);");
        mGridView.setOnScrollListener(this);
        mGridView.setOnItemClickListener(this);
        mGridView.setOnItemLongClickListener(this);


        initBottomMenu();


        /*----侧边抽屉和ListView的字体及颜色设置----*/
       /* toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);//public abstract class CommonActivity extends AppCompatActivity*/

        ActionBar ab = getActionBar();
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setHomeButtonEnabled(true);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerLayout.setScrimColor(0x00000000);
        //设置阴影 mDrawerLayout.setDrawerShadow(R.drawable.trans, GravityCompat.START);
        mDrawerList = (ListView) findViewById(R.id.navigation_drawer);
        drawerArrow = this.getDrawerArrow();
        mDrawerToggle =this.getActionBarDrawerToggle();
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        mDrawerToggle.syncState();
        String[] itemTitle = getResources().getStringArray(R.array.item_title);
        int[] itemIconRes ={
                R.drawable.list_user,
                R.drawable.list_sh,
                R.drawable.list_address,
                R.drawable.list_data,
        };

        list=new ArrayList<ContentModel>();
        for (int i = 0; i < itemTitle.length; i++) {
            ContentModel item = new ContentModel(itemIconRes[i], itemTitle[i]);
            list.add(item);

        }
        adapter=new DrawerListAdapter(this,list);
        mDrawerList.setAdapter(adapter);
        iniDrawerListListener();
    }

    private DrawerArrowDrawable getDrawerArrow(){
        DrawerArrowDrawable mdrawerArrow = new DrawerArrowDrawable(this) {
            @Override
            public boolean isLayoutRtl() {
                return false;
            }
        };
        return  mdrawerArrow;
    }
    private ActionBarDrawerToggle getActionBarDrawerToggle(){
        ActionBarDrawerToggle   mDrawerToggle1 = new ActionBarDrawerToggle(this, mDrawerLayout,
                drawerArrow, R.string.drawer_open,
                R.string.drawer_close) {
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu();
            }
        };
        return  mDrawerToggle1;
    }
    private void iniDrawerListListener(){
        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                switch (position) {
                    case 0:
                        mDrawerToggle.setAnimateEnabled(false);
                        drawerArrow.setProgress(1f);
                        Intent intent = new Intent();
                        intent.setClass(WelcomeActivity.this,InfoActivity.class);
                        startActivity(intent);
                        break;
                    case 1:
                        mDrawerToggle.setAnimateEnabled(false);
                        drawerArrow.setProgress(0f);
                        Intent intent1 = new Intent();
                        intent1.setClass(WelcomeActivity.this, InfoActivity.class);
                        startActivity(intent1);
                        break;
                    case 2:
                        mDrawerToggle.setAnimateEnabled(true);
                        mDrawerToggle.syncState();
                        Intent intent2 = new Intent();
                        intent2.setClass(WelcomeActivity.this, InfoActivity.class);
                        startActivity(intent2);
                        break;
                    case 3:
                        mDrawerToggle.setAnimateEnabled(true);
                        Intent intent3 = new Intent();
                        intent3.setClass(WelcomeActivity.this, CartActivity.class);
                        startActivity(intent3);
                        mDrawerToggle.syncState();
                        break;
                }

            }
        });
    }
    private void initListViewListener() {
        productListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i("welcome", "Welcome " + Integer.toString(position));
                Product product = productList.get(position);
                Intent intent = new Intent();
                intent.putExtra("productId", product.getProductId());
                intent.setClass(WelcomeActivity.this, ProductDetailActivity.class);
                startActivity(intent);
            }
        });
    }

    private void prepareData() {
        // request data
        productList = new ArrayList<Product>();
        BaseModel model = new BaseModel();
        model.setCommandId(Constant.COMMAND_GETHOT);
        ShoppingController.doQueryHot(this, model);
    }

    @Override
    public void onResponseMessage(BaseResponse response) {
        super.onResponseMessage(response);
        ResponseHotJson hotJson = (ResponseHotJson)response;
        if (hotJson.getResult() == 0) {
            for(ResponseProduct product: hotJson.getProducts()) {
                Product product1 = new Product();
                product1.setImageUrl("http://10.214.143.25:8080/" + product.getProductImage());
                product1.setProductName(product.getProductName());
                product1.setPrice(product.getProductPrice());
                product1.setProductId(product.getProductId());
                productList.add(product1);
            }
            Log.i("welcome", "productList updated");
            pAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void initBottomMenu() {
        transBtn=(Button)findViewById(R.id.transButton);
        transBtn.getBackground().setAlpha(200);//更改半透明度
        imageViewIndex = (ImageView) findViewById(R.id.menu_home_img);
//        imageViewIndex.setOnTouchListener(indexListener);
        imageViewIndex.setImageResource(R.drawable.menu_home_pressed);

        imageViewShopping = (ImageView) findViewById(R.id.menu_shopping_cart_img);
        imageViewShopping.setOnTouchListener(shoppingListener);
        imageViewShopping.setImageResource(R.drawable.menu_shopping_cart_released);

        imageViewMyInfo = (ImageView) findViewById(R.id.menu_personal_center_image);
        imageViewMyInfo.setOnTouchListener(myInfoListener);
        imageViewMyInfo.setImageResource(R.drawable.menu_my_info_released);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
                mDrawerLayout.closeDrawer(mDrawerList);
            } else {
                mDrawerLayout.openDrawer(mDrawerList);
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
       // getMenuInflater().inflate(R.menu.menu_sgv_dynamic, menu);
        return true;
    }


    @Override
    protected void onSaveInstanceState(final Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putStringArrayList(SAVED_DATA_KEY, mData);
    }

    @Override
    public void onScrollStateChanged(final AbsListView view, final int scrollState) {
        Log.d(TAG, "onScrollStateChanged:" + scrollState);
    }

    @Override
    public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount, final int totalItemCount) {
        Log.d(TAG, "onScroll firstVisibleItem:" + firstVisibleItem +
                " visibleItemCount:" + visibleItemCount +
                " totalItemCount:" + totalItemCount);
        // our handling
        if (!mHasRequestedMore) {
            int lastInScreen = firstVisibleItem + visibleItemCount;
            if (lastInScreen >= totalItemCount) {
                Log.d(TAG, "onScroll lastInScreen - so load more");
                mHasRequestedMore = true;
                onLoadMoreItems();
            }
        }
    }


    private void onLoadMoreItems() {
      /*  final ArrayList<Product> sampleData =   new ArrayList<Product>();
        BaseModel model = new BaseModel();
        model.setCommandId(Constant.COMMAND_GETHOT);
        ShoppingController.doQueryHot(this, model);
        for (Product data : sampleData) {
            pAdapter.add(data);
        }
        // stash all the data in our backing store
        mData.addAll(sampleData);
        // notify the adapter that we can update now
        pAdapter.notifyDataSetChanged();
        mHasRequestedMore = false;*/
        pAdapter.notifyDataSetChanged();
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        Toast.makeText(this, "Item Clicked: " + position, Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
    {
        Toast.makeText(this, "Item Long Clicked: " + position, Toast.LENGTH_SHORT).show();
        return true;
    }
}
